package com.starblink.android.common.web

import android.Manifest
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.view.animation.AccelerateDecelerateInterpolator
import androidx.core.net.toUri
import androidx.core.view.postDelayed
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.PermissionUtils
import com.google.zxing.Result
import com.king.zxing.CameraScan
import com.king.zxing.CameraScan.OnScanResultCallback
import com.king.zxing.DecodeConfig
import com.king.zxing.DecodeFormatManager
import com.king.zxing.DefaultCameraScan
import com.king.zxing.analyze.MultiFormatAnalyzer
import com.king.zxing.config.ResolutionCameraConfig
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.base.activity.BaseTVMActivity
import com.starblink.android.basic.ext.gone
import com.starblink.android.basic.ext.showCameraAccessDialog
import com.starblink.android.basic.ext.toast
import com.starblink.android.basic.ext.visible
import com.starblink.android.basic.extension.navigateUri
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.urllink.UriLinkConfig.isSchemaGUANG
import com.starblink.basic.ext.appScreenHeight
import com.starblink.basic.route.RoutePage
import com.starblink.web.BuildConfig
import com.starblink.android.common.databinding.ActivityCustomScanBinding

@Route(path = RoutePage.Web.PAGE_GLOBAL_SCAN)
class CustomScanActivity : BaseTVMActivity<ActivityCustomScanBinding, BaseViewModel>(),
    OnScanResultCallback {

    @JvmField
    @Autowired(name = RoutePage.Web.ARG_WHITE_LIST)
    var withWhiteList = false

    @JvmField
    @Autowired(name = RoutePage.Web.ARG_AUTO_JUMP)
    var ifAutoJump = true

    private var mCameraScan: CameraScan? = null

    private var scanAnimator: ObjectAnimator? = null

    private var hasResult = false

    private val whiteHostList by lazy {
        mutableListOf("getguang.com", "starblink.co")
    }

    override fun initViewBinding(): ActivityCustomScanBinding {
        return ActivityCustomScanBinding.inflate(layoutInflater)
    }

    override fun initView() {
        super.initView()
        pageExposure(SpmPageDef.SCAN_CAMERA)

        viewBinding.btnCancel.trackData(
            element = SpmElementDef.ScanCameraCancel,
            page = SpmPageDef.SCAN_CAMERA,
            onlyHit=true
        )
        viewBinding.btnCancel.setOnClickListener {
            onBackPressed()
        }

        PermissionUtils.permission(Manifest.permission.CAMERA)
            .callback { isAllGranted, granted, _, _ ->
                if (isAllGranted) {
                    initScanner()
                } else {
                    showCameraAccessDialog()
                }
            }.request()
    }


    override fun onResume() {
        super.onResume()
        mCameraScan?.setAnalyzeImage(true)
        viewBinding.textTip.gone()
        viewBinding.textTip.postDelayed(20000L) {
            if (!hasResult) {
                viewBinding.textTip.visible()
            }
        }
    }

    override fun onPause() {
        super.onPause()
        mCameraScan?.setAnalyzeImage(false)
    }

    override fun onDestroy() {
        scanAnimator?.cancel()
        mCameraScan?.release()
        super.onDestroy()
    }

    override fun onScanResultCallback(result: Result?): Boolean {
        //如果需支持连扫，返回true即可
        if (BuildConfig.DEBUG) {
            toast(result?.text)
        }
        hasResult = result?.text != null
        if(ifAutoJump){
            result?.text?.let {
                mCameraScan?.setAnalyzeImage(false)
                it.toUri().run {
                    if (withWhiteList) {
                        if (this.host?.matchWhiteList() == true || it.isSchemaGUANG()) {
                            navigateUri(this, onLost = {
                                navigationTo(RoutePage.GCONFIG.G_NOT_FOUNT)
                            })
                        } else {
                            navigationTo(RoutePage.GCONFIG.G_NOT_FOUNT)
                        }
                    } else {
                        navigateUri(this, onLost = {
                            navigationTo(RoutePage.GCONFIG.G_NOT_FOUNT)
                        })
                    }
                }

            }
        }
        return ifAutoJump
    }

    private fun initScanner() {

        //初始化解码配置
        val decodeConfig = DecodeConfig()
        decodeConfig.setHints(DecodeFormatManager.QR_CODE_HINTS).isFullAreaScan =
            true //设置是否全区域识别，默认false


        mCameraScan = DefaultCameraScan(this, viewBinding.previewView)
        mCameraScan!!.setOnScanResultCallback(this)
            .setAnalyzer(MultiFormatAnalyzer(decodeConfig))
            .setVibrate(true)
            .setCameraConfig(
                ResolutionCameraConfig(
                    this,
                    ResolutionCameraConfig.IMAGE_QUALITY_720P
                )
            )
            .startCamera()


        viewBinding.imgAnim.visible()
        scanAnimator = ObjectAnimator.ofFloat(
            viewBinding.imgAnim,
            "translationY",
            0f,
            appScreenHeight * 0.8f,
        ).apply {
            repeatMode = ValueAnimator.RESTART
            repeatCount = ValueAnimator.INFINITE
            duration = 2000L
            interpolator = AccelerateDecelerateInterpolator()
            start()
        }
    }

    private fun String.matchWhiteList(): Boolean {
        return whiteHostList.indexOfFirst { this.endsWith(it) } > -1
    }
}